package data

import (
	"digitalhuman/internal/conf"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/go-kratos/kratos/v2/log"
)

type DsmData struct {
	DsClient *dysmsapi.Client
	Config   *conf.Data
}

func NewDsData(config *conf.Data) *DsmData {
	dsData := &DsmData{Config: config}
	c, err := newDyApiClient(config)
	if err != nil {
		panic(err)
	}
	dsData.DsClient = c

	return dsData
}

func newDyApiClient(c *conf.Data) (*dysmsapi.Client, error) {
	accessKeyId, accessKeySecret := tea.String(c.AliDys.AccessKeyId), tea.String(c.AliDys.AccessKeySecret)
	config := &openapi.Config{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
	}
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	client, err := dysmsapi.NewClient(config)
	if err != nil {
		return nil, err
	}

	return client, nil
}

func (d *DsmData) SendMessage(phone string, code int) bool {
	request := &dysmsapi.SendSmsRequest{}
	// 该参数值为假设值，请您根据实际情况进行填写
	request.SetPhoneNumbers(phone)
	request.SetSignName(d.Config.AliDys.SignName)
	request.SetTemplateCode("SMS_465392870")
	request.SetTemplateParam(fmt.Sprintf("{'code':%d}", code))

	response, err := d.DsClient.SendSms(request)
	if err != nil {
		log.Error("短信发送失败", err)
		return false
	}

	fmt.Println(tea.StringValue(response.Body.Message))
	return true
}
